//
//  ScenicDetailVC.swift
//  LeTu
//
//  Created by g1 on 2024/1/11.
//

import UIKit
import BUAdSDK

class ScenicDetailVC: BaseViewController {

    private var viewModel: ScenicDetailVM
    /// 当前播放的stortModel
    private var currentPlayStoryModel: ScenicStoryModel?
    
    // 激励广告
    private var rewardAd: BUNativeExpressRewardedVideoAd?
    
    // 广告播放index
    private var adPlayIndex = -1
    
    init(scenicModel: ScenicModel) {
        viewModel = ScenicDetailVM(scenicModel: scenicModel)
        super.init()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        refreshData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(paymentSuccessNotification), name: NSNotification.Name("PaymentSuccessNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NSNotification.Name("LoginSuccessNotification"), object: nil)
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        sectionHeader.switchView.isOn = AppAudioManager.shared.isAutoPlay
        currentPlayStoryModel = AppAudioManager.shared.currentStoryModel
        storyTableView.reloadData()
        eventHandle()
    }
    override func refreshData() {
        headView.setScenicModel(viewModel.scenicModel)
        getScenicInfo()
    }
    @objc private func paymentSuccessNotification() {
        kUserManager.getUserInfomation { _ in }
        reloadData()
    }
    private func eventHandle() {
        AppAudioManager.shared.completePlayBlock = { [weak self] flag, index, storyModel in
            guard let strongSelf = self else { return }
            if flag == true {
                strongSelf.currentPlayStoryModel = storyModel
                strongSelf.storyTableView.reloadData()
            }
        }
    }
    private func getScenicInfo() {
        
        viewModel.getScenicDetails { [weak self] dialog in
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                if dialog.code == 200 {
                    
                    // 存储数据
                    StoryDataManager.shard.setScenicId(scenicModel: strongSelf.viewModel.scenicModel)
                    
                    strongSelf.sectionHeader.setList(classifyItems: StoryDataManager.shard.classifyItems, index: strongSelf.viewModel.currentClassifysIndex)
                    strongSelf.headView.setScenicModel(strongSelf.viewModel.scenicModel)
                    strongSelf.getData(isLoad: false)
                    strongSelf.navbar.setTitle(LanguageManager.shared.currentLanguage == .en ? strongSelf.viewModel.scenicModel.englishName:strongSelf.viewModel.scenicModel.name)
                    

                } else {
                    strongSelf.showMessage(message: dialog.message)
                }
            }
        }
        
    }
    @objc private func reloadData() {
        getScenicInfo()
        getData(isLoad: false)
    }
    private func getData(isLoad: Bool) {
        
        guard viewModel.isLoadAllSuccess == false else { return }
        
        if isLoad == false {
            getAllScenics()
            storyTableView.footerResetNoMoreData()
        }
        
        showIndicator()
        StoryDataManager.shard.getScenics(isLoad: isLoad, currentClassifysIndex: viewModel.currentClassifysIndex) { [weak self] dialog in
            
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                strongSelf.hideIndicator()
            }
            guard AppAudioManager.shared.currentClassifysIndex == strongSelf.viewModel.currentClassifysIndex else { return }
            
            DispatchQueue.main.async {
                                
                guard strongSelf.viewModel.isLoadAllSuccess == false else { return }

                if isLoad {
                    strongSelf.storyTableView.footerEndRefreshing()
                } else {
                    strongSelf.storyTableView.headerEndRefreshing()
                }
                
                if dialog.code != 200 {
                    strongSelf.showMessage(message: dialog.message)
                }
                
                if let datas = dialog.data as? [ScenicStoryModel], datas.count == 0 || strongSelf.viewModel.sourceArr.count % StoryDataManager.shard.pageSize > 0 {
                    strongSelf.storyTableView.footerEndRefreshingWithNoMoreData()
                }
                UIView.performWithoutAnimation {
                    strongSelf.storyTableView.reloadData()
                }
                
            }
            
        }
        
    }
    // 获取全部景点
    private func getAllScenics() {
        
        StoryDataManager.shard.getAllScenics(scenicId: viewModel.scenicModel.id, currentClassifysIndex: viewModel.currentClassifysIndex) { [weak self] dialog in
            
            guard let strongSelf = self, let classifysIndex = dialog.data as? Int else { return }
            
            DispatchQueue.main.async {
                
                // 设置播放器列表
                if AppAudioManager.shared.currentClassifysIndex == classifysIndex && classifysIndex < StoryDataManager.shard.classifyItems.count {
                    AppAudioManager.shared.setPlayList(StoryDataManager.shard.classifyItems[classifysIndex].sourceArr, currentIndex: AppAudioManager.shared.currentURLIndex, listenPermission: strongSelf.viewModel.scenicModel.listenPermission)
                }
                
                // 结束加载
                strongSelf.storyTableView.footerEndRefreshingWithNoMoreData()
                
                // 更新UI
                UIView.performWithoutAnimation {
                    strongSelf.storyTableView.reloadData()
                }
                
            }
            
        }
        
    }
    override func backAction() {
        super.backAction()
        
        StoryDataManager.shard.reserManager()
        //AppAudioManager.shared.destroyPlayer()
    }
    
    // MARK: - configUI
    func configUI() {
        
        view.addSubview(storyTableView)
        storyTableView.addSubview(headView)
        view.addSubview(navbar)
        
        storyTableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        let headViewHeight = ScenicDetailHeadView.getHeadHeight(scenicModel: viewModel.scenicModel)
        headView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.width.equalTo(screenWidth)
            make.top.equalTo(-headViewHeight)
            make.height.equalTo(headViewHeight)
        }
        navbar.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(Size.navigationBarHeight)
        }
        
        storyTableView.delegate = self
        storyTableView.dataSource = self
        storyTableView.register(cellClass: ScenicDetailStoryTableViewCell.self)
        storyTableView.tableHeaderView = sectionHeader
        storyTableView.addRefreshFooterCallback { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.getData(isLoad: true)
        }
        
        navbar.backHandle = { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.backAction()
        }
        sectionHeader.repeatHandle = { isOn in
            AppAudioManager.shared.isAutoPlay = isOn
        }
        sectionHeader.selectClassifyHandle = { [weak self] _ , index in
            guard let strongSelf = self else { return }
            strongSelf.viewModel.currentClassifysIndex = index
            strongSelf.storyTableView.reloadData()
            strongSelf.getData(isLoad: false)
        }
        
        storyTableView.contentInset = UIEdgeInsets(top: headViewHeight, left: 0, bottom: 0, right: 0)
        storyTableView.contentOffset = CGPoint(x: 0, y: -headViewHeight-44)
        
    }
    private lazy var headView = ScenicDetailHeadView()
    private lazy var sectionHeader = ScenicDetailSectionView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 58))
    private lazy var storyTableView: UITableView = {
        let storyTableView = UITableView()
        storyTableView.tableFooterView = UIView()
        storyTableView.showsVerticalScrollIndicator = false
        return storyTableView
    }()
    private lazy var navbar = ScenicDetailNavBar(title: LanguageManager.shared.currentLanguage == .en ? viewModel.scenicModel.englishName:viewModel.scenicModel.name)
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension ScenicDetailVC: TransferEventReceivable {
    
    enum TransferEvent: TransferEventType {
        case playStory(Int)
        case lockStory(Int)
        case tryOutStory(Int)
        case collectScenic
    }
    
    func receive(event: TransferEventType) {
        
        switch event {
        case ScenicDetailVC.TransferEvent.playStory(let index), ScenicDetailVC.TransferEvent.tryOutStory(let index):
            playAudio(index: index)
        case ScenicDetailVC.TransferEvent.lockStory(let index):
            guard kUserManager.isLogin else {
                kUserManager.toLogin()
                return
            }
            toPay(index: index)

        case ScenicDetailVC.TransferEvent.collectScenic:
            guard kUserManager.isLogin else {
                kUserManager.toLogin()
                return
            }
            let isCollect = viewModel.scenicModel.hasCollected ? 2:1
            CollectVM.collectScenic(params: ["id": viewModel.scenicModel.id, "collection": isCollect]) { [weak self] dialog in
                guard let strongSelf = self else { return }
                DispatchQueue.main.async {
                    if dialog.code == 200 {
                        strongSelf.viewModel.scenicModel.hasCollected = !strongSelf.viewModel.scenicModel.hasCollected
                        strongSelf.headView.setScenicModel(strongSelf.viewModel.scenicModel)
                    }
                }
            }
            
        default:
            break
        }
        
    }
    private func toPay(index: Int) {
        
        if kUserManager.isLogin {
            show(PaymentVC(scenicModel: viewModel.scenicModel), sender: nil)
        } else {
            showDetailViewController(LoginVC(viewType: .authCode), sender: nil)
        }
        
//        let lockAlertView = LockScenicAlertView()
//        lockAlertView.clickBuyHandle = { [weak self] in
//            guard let strongSelf = self else { return }
//            if kUserManager.isLogin {
//                strongSelf.show(PaymentVC(scenicModel: strongSelf.viewModel.scenicModel), sender: nil)
//            } else {
//                strongSelf.showDetailViewController(LoginVC(viewType: .authCode), sender: nil)
//            }
//        }
//        lockAlertView.clickCheckAadHandle = { [weak self] in
//            guard let strongSelf = self else { return }
//            strongSelf.adPlayIndex = index
//            strongSelf.getAdData()
//        }
//        lockAlertView.show()
    }
    
    /// 播放音频
    func playAudio(index: Int, isForce: Bool = false) {
        if kUserManager.isLogin {
            let storyModel = viewModel.sourceArr[index]
            guard viewModel.scenicModel.listenPermission == true || (viewModel.scenicModel.listenPermission == false && storyModel.payStatus == 0) || isForce == true else {
                toPay(index: index)
                return
            }
            AppAudioManager.shared.setPlayList(viewModel.sourceArr, currentIndex: index, listenPermission: viewModel.scenicModel.listenPermission)
            
            if viewModel.sourceArr[index] != currentPlayStoryModel || (viewModel.sourceArr[index] == currentPlayStoryModel && !AppAudioManager.shared.isPlaying) || isForce == true {
                currentPlayStoryModel = viewModel.sourceArr[index]
                AppAudioManager.shared.createAudioPlayer(currentIndex: index, pictureUrl: viewModel.scenicModel.picUrl, currentClassifysIndex: viewModel.currentClassifysIndex)
            } else {
                if !AppAudioManager.shared.isPlaying {
                    AppAudioManager.shared.playAudio()
                }
            }
            show(ScenicStoryVC(scenicModel: viewModel.scenicModel, storyModel: storyModel, currentClassifysIndex: viewModel.currentClassifysIndex, isTemp: isForce), sender: nil)
        } else {
            showDetailViewController(LoginVC(viewType: .authCode), sender: nil)
        }
    }
    
}

extension ScenicDetailVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.sourceArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(ScenicDetailStoryTableViewCell.self, indexPath: indexPath)
        if indexPath.row < viewModel.sourceArr.count {
            let stortyModel = viewModel.sourceArr[indexPath.row]
            cell.setStoryModel(stortyModel, index: indexPath.item, isPlaying: stortyModel == currentPlayStoryModel && AppAudioManager.shared.isPlaying == true)
            cell.setListenPermission(viewModel.scenicModel.listenPermission)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        playAudio(index: indexPath.row)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let contentInsetTop = ScenicDetailHeadView.getHeadHeight(scenicModel: viewModel.scenicModel)
        let offsetY = scrollView.contentOffset.y
        
        if offsetY <= -contentInsetTop {
            headView.snp.updateConstraints { make in
                make.top.equalTo(-abs(offsetY))
                make.height.equalTo(abs(offsetY))
            }
        }
        
        headView.snp.updateConstraints { make in
            make.top.equalTo(offsetY <= -contentInsetTop ? -abs(offsetY):-contentInsetTop)
            make.height.equalTo(offsetY <= -contentInsetTop ? abs(offsetY) : contentInsetTop)
        }
              
        //MYLog(offsetY)
        let topMinScale = ScenicDetailHeadView.getHeadImgViewHeight() + 16 - 88
        
        var imgScrollY = abs(offsetY) - contentInsetTop
        if offsetY < -contentInsetTop {
            imgScrollY = 0
        } else if offsetY > -topMinScale {
            imgScrollY = abs(-topMinScale) - contentInsetTop
        }
        navbar.changeNaviBarUIStatus(imgScrollY)
    }
    
}

// MARK: - 加载激励广告
extension ScenicDetailVC: BUNativeExpressRewardedVideoAdDelegate {
    
    // 加载广告信息
    private func getAdData() {
        rewardAd = kAdsManager.loadRewardedTheAdvertising(delegate: self)
        if rewardAd != nil {
            rewardAd?.loadData()
        } else {
            kAdsManager.requestAdsIdList { [weak self] dialog in
                guard let strongSelf = self else { return }
                DispatchQueue.main.async {
                    strongSelf.rewardAd = kAdsManager.loadRewardedTheAdvertising(delegate: strongSelf)
                    strongSelf.rewardAd?.loadData()
                }
            }
        }
        
    }
    
    func nativeExpressRewardedVideoAdDidLoad(_ rewardedVideoAd: BUNativeExpressRewardedVideoAd) {
        // 广告加载成功之后，可以调用展示方法，按照实际需要调整代码位置
        rewardedVideoAd.show(fromRootViewController: self)
    }
    
    func nativeExpressRewardedVideoAdDidClose(_ rewardedVideoAd: BUNativeExpressRewardedVideoAd) {
        print("点击了关闭")
        
        guard adPlayIndex != -1 else { return }
        playAudio(index: adPlayIndex, isForce: true)

    }
    
}

